package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.controller.UploadController;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author MiniApple
 * @date 2020/6/7 - 11:17
 */
@Service
public class UploadService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg");

    //日志需要的类对象通常是当前类
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    //文件存储客户端
    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadImage(MultipartFile file){
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();

        //1 文件类型
        String contentType = file.getContentType();
        if(!CONTENT_TYPES.contains(contentType)){
            //不建议直接用字符串拼接，效率比较低
            LOGGER.info("文件上传失败：{}，文件类型不合法",originalFilename);
            return null;
        }

        try {
            //2 校验文件内容(ImageIO还可以用于图片验证码)
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            //严谨一点的话还可以加上判断文件的高度和和宽度
            if (bufferedImage == null){
                //不建议直接用字符串拼接，效率比较低
                LOGGER.info("文件上传失败：{}，文件内容不合法",originalFilename);
                return null;
            }

            //3 保存到服务器
            //file.transferTo(new File("D:\\StudyFile\\images\\" + originalFilename));
            //需要的参数为：文件流，文件大小，文件后缀，元数据
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);


            //4 返回url路径(需要拼接的是带组的路径)
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            LOGGER.info("文件上传失败：{}，服务器异常！",originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}
